<template>
    <div id="add-edit-model">
        <el-dialog
            :title="$t('xK9kG3ePv2jAy469EbNk')"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="769px" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
                <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="auto" :rules="rules">
                    <el-row :gutter="35">
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item :label="$t('qyLcQAgMgOdLj0Zl6rRQr')" prop="CompanyNum">
                                <el-select @change="CompanyChange" filterable v-model="ruleForm.CompanyNum" :placeholder="$t('w6yAsWzlwm9p7_4cqFcHy')">
                                    <el-option
                                    v-for="item in CompanyOptions"
                                    :key="item.code"
                                    :label="item.value"
                                    :value="item.code"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item :label="$t('0KhQqhWmdquUAxIfKo4d')" prop="InformStaffID">
                                <el-select @change="InformStaffIDChange" filterable v-model="ruleForm.InformStaffID" :placeholder="$t('0x3FmwXfXvNhrbcV9AcK')">
                                    <el-option
                                    v-for="item in InformStaffIDOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.jobNum"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col><el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item :label="$t('1uFSzFJjtbIaxwG9Ogd')" prop="MaterialTypeIds">
                                <el-input
                                    disabled
                                    type="textarea"
                                    :rows="2"
                                    :placeholder="$t('y5VWdo1wOn1McmWghSbZ')"
                                    v-model="codeTextarea" 
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item :label="$t('pmSAcdCmOvXo9bNNxs5tO')" prop="MaterialTypeIds">
                                <el-input
                                    disabled
                                    type="textarea"
                                    :rows="2"
                                    :placeholder="$t('laXdCypupi0UtWyPxr6kE')"
                                    v-model="nameTextarea" 
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
            <el-card shadow="hover" :body-style="{ paddingBottom: '0' }" style="margin-top: 10px;">
                <div class="wl-tyle">{{ $t('2QaVkzbB2rqK7kZoRKucS') }}</div>
                <el-form ref="queryForm" :inline="true" label-width="auto">
                    <el-form-item :label="$t('rPuTdbd1foSRohVlfJQK')">
                        <el-input v-model="searchOne" :placeholder="$t('0iCxiqIl04cr5jgQc1uF')" clearable  />
                    </el-form-item>
                    <el-form-item >
                        <el-button @click="resetClick" icon="ele-Refresh"> {{ $t('eE3IedvHkKmnppI9FzCa7') }} </el-button>
                        <el-button @click="searchClick" type="primary" icon="ele-Search"> {{ $t('5fM07d4lwWlNvcG51m0ao') }} </el-button>
                        <el-button v-if="$hasPer('materialClass:add')" @click="addClick" icon="ele-Plus" type="primary"> {{ $t('qb5Zm1pEsg0EjMphQt5dB') }} </el-button>
                    </el-form-item>
                </el-form>
                <el-table 
                    :data="list" 
                    style="width: 100%"
                    v-loading="loading"
                    element-loading-background="rgba(0, 0, 0, 0.8)"
                    :row-key="getRowKey"
                    border
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column :label="$t('oFzzBrvElmORaMvCbSnPt')" align="center" type="selection" width="55" />
                    <el-table-column :label="$t('yjYpiK9EqdAxjSntzTnhC')" prop="typeName" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.typeName" :placeholder="$t('wehJeThIbC6cpLEcIOd6')" clearable />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('d9iNhinwXriKvLcu_6bE')" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.typeNumber" :placeholder="$t('mcB86Om6HZl4GwCfThh')" clearable />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('zKDqLt0KBzwdoJgiQgoj')" align="center" >
                        <template #default="scope">
                            <el-button @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> {{ $t('eFGvRkuRtNhwYr8Ih5z7v') }} </el-button>
                            <el-popconfirm
                                confirm-button-text="确认"
                                cancel-button-text="取消"
                                icon="InfoFilled"
                                icon-color="#626AEF"
                                :title="$t('w0AiVwUcoxhuhSFhbuv6g')"
                                @confirm="confirm(scope.row)"
                            >
                                <template #reference>
                                    <el-button class="icon-e" icon="ele-Delete" size="small" text type="danger"> {{ $t('ko8YfTozEhXs5Fu8Vn9c') }} </el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    v-model:currentPage="pageNo"
                    v-model:page-size="pageSize"
                    :total="totalRows"
                    :page-sizes="[10, 20, 50, 100]"
                    small
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    layout="total, sizes, prev, pager, next, jumper"
                />
            </el-card>
            <template #footer>
                <el-button @click="cancelUseClick">{{ $t('gJikJmcygxvlVId7NvzSu') }}</el-button>
                <el-button type="primary" :disabled="repeatDis" @click="submitForm(ruleFormRef)">{{ $t('hfPwhz0wXrlEiXoAqXs9W') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue'
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus'
import { cgMaterialTypeAdd, cgDistributeTypeAdd , cgMaterialTypeDelete , sysDictTypeDropDown , sysEmpSelector , cgMaterialTypePage } from '/@/api/manage/manage'
import getTableData from '/@/utils/getTableData'
import { stat } from 'fs'
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
const { proxy } = useCurrentInstance();
const $t = proxy.$t;
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
    list: any[], // 数组
    pageNo: number, // 当前页
    pageIndex: number,
    pageSize: number, // 一页的数量
    totalRows: number, // 总条数
    totalPage: number, // 总页数
}
/*** form 表单数据类型 */
type ruleFormType = {
    InformStaffID: any, // 员工工号
    Company: String, // 公司名称
    CompanyNum: String, // 公司编码
    MaterialTypeIds: any | [], // 物料类别id数组
}
export default defineComponent( {
    name: 'add-edit-model',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const ruleFormRef = ref()
        const CompanyOptions = ref()
        const InformStaffIDOptions = ref()
        const nameTextarea = ref()
        const codeTextarea = ref()
        const searchOne = ref('')
        let pageNo:number = 1
        let pageSize:number = 10
        // let setArr:any[] = []
        const loading = ref(false)

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType,
            list: [], // 数组
            pageNo: 1, // 当前页
            pageIndex: 1,
            pageSize: 10, // 一页的数量
            totalRows: 0, // 总条数
            totalPage: 0, // 总页数
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            InformStaffID: [
				{ required: true, message: $t('lzj5rY_1GasyFs6W3DqYe'), trigger: 'change' },
			],
            CompanyNum: [
				{ required: true, message: $t('rheGteQQwoMlcd7yNGs'), trigger: 'change' },
			],
            MaterialTypeIds: [
				{ required: true, message: $t('16wqHfma3KQlGitLCfyWo'), trigger: 'blur' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        const getRowKey = (row:any) => {
            return row.dpriceConfId
        }

        /*** delStrFun 删除指定位置字符 */
        const delStrFun = (str:any,n: any) => {
            str = [...str]
            let idx = str.lastIndexOf(n)
            str.splice(idx , 1)
            return str.join('')
        }

        /*** handleSelectionChange 复选框选中事件 */
        const handleSelectionChange = (val:any) => {
            console.log(val,'val')
            // const nameTextarea = ref()
            // const codeTextarea = ref()
            let setName = ''
            let setCade = ''
            let needArr:any = []
            val.map((i:any) => {
                setName += (toRaw(i).typeName + '，')
                setCade += (toRaw(i).typeNumber + '，')
                needArr.push(toRaw(i).id)
            })
            nameTextarea.value = delStrFun(setName,'，')
            codeTextarea.value = delStrFun(setCade,'，')
            state.ruleForm.MaterialTypeIds = needArr
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        // 设置序列号
        const indexMethod = (index: number) => {
            if (state.pageNo > 1) {
                return index + 1 + (Number(state.pageNo) - 1) * Number(state.pageSize);
            } else {
                return index + 1;
            }
        }

        const handleSizeChange = (val:any) => {
            pageSize = val
            GetData(pageNo,val)
        } 

        const handleCurrentChange = (val:any) => {
            pageNo = val
            GetData(val,pageSize)
        }

        let isAllowNum = 0
        let addNum = 0
        const addClick = () => {
            isAllowNum = isAllowNum += 1
            if(isAllowNum > 1){
                // console.log(state.ruleForm.list[addNum - 1].checkerID,'checkerID')
                if(state.list[addNum - 1].checkerID === ''){
                    ElMessage({
                        message: $t('x4V8LmutnEMz2bvXbEgan'),
                        type: 'warning',
                        duration: 1000,
                    })
                    return
                }
            }
            addNum = addNum += 1
            let personObj = {
                addNum : addNum, // 自增主键
                typeName: '',
                typeNumber: '',
            }
            state.list.push(personObj)
            // console.log(state.ruleForm.list,'list新增')
        }

        /*** confirm 移除 */
        const confirm = async (t:any) => {
            if(toRaw(t).id){
                let param = {
                    id: toRaw(t).id
                }
                let res:any = await cgMaterialTypeDelete(param)
                if(res.success){
                    GetData(pageNo,pageSize)
                }
            }else{
                state.list = state.list.filter((i:any) => {
                    return i.addNum !== t.addNum
                })
                if(state.list.length === 0){
                    addNum = 0
                    isAllowNum = 0
                }else{
                    state.list.map((m:any,i:any) => {
                        m.addNum = i + 1
                    })
                    addNum = state.list.length
                }
            }
        }

        /*** nodeClick 保存按钮 */
        const nodeClick = (val:any) => {
            console.log(val,'val')
            let param:any = {}
            if(val.typeName === ''){
                ElMessage({
                    message: $t('og0XsMwHi2yp0Ez5XhMuw'),
                    type: 'warning',
                    duration: 1000,
                })
                return
            }
            if(val.typeNumber === ''){
                ElMessage({
                    message: $t('5MPyy8PPsikIntvGxP4Dz'),
                    type: 'warning',
                    duration: 1000,
                })
                return
            }
            if(val.id){
                param.id = val.id
            }
            param.typeName = val.typeName
            param.typeNumber = val.typeNumber
            let res:any = cgMaterialTypeAdd(param)
            if(res.success){
                GetData(pageNo,pageSize)
            }
        }

        /*** CompanyChange 负责公司区域改变事件 */
        const CompanyChange = (val:any) => {
            console.log(val,'val')
            let obj = CompanyOptions.value.find((i:any) => {
                return i.code === val
            })
            state.ruleForm.Company = toRaw(obj).value
        }

        /*** InformStaffIDChange 员工信息改变事件 */
        const InformStaffIDChange = (val:any) => {
            // console.log(val,'val')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let param = toRaw(state.ruleForm)
                    console.log(param,'param')
                    let res:any = await cgDistributeTypeAdd(param)
                    if(res.success){
                        state.repeatDis = true
                        ctx.emit('controlUseClick','success')
                    }else{
                        ctx.emit('controlUseClick','')
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            // ruleFormRef.value.resetFields()
        }

        /*** GetInfo 获取数据 */
        const GetInfo = async () => {
            // 获取数据字典数据
            try {
                let param = {
                    Code: 'Applicant_Type'
                }
                let res:any = await sysDictTypeDropDown(param)
                if(res.success){
                    // console.log(res.data,'数据库字典')
                    CompanyOptions.value = res.data
                }
            } catch (err) { return }

            // 获取员工信息
            try {
                let res:any = await sysEmpSelector()
                if(res.success){
                    // console.log(res.data,'员工信息')
                    InformStaffIDOptions.value = res.data
                }
            } catch (err) { return }
        }

        /*** GetData 分页获取物料类别列表 */
        const GetData = async (n:number,s:number) => {
            loading.value = true
            let param:any = {}
            param.pageNo = n
            param.pageSize = s
            if(searchOne.value !== ''){
                param.searchValue = searchOne.value
            }
            let res:any = await cgMaterialTypePage(param)
            if(res.success){
                // console.log(res.data.rows,'物料类别')
                res.data.rows.map((i:any,t:any) => {
                    i.addNum = t + 1
                })
                state.list = res.data.rows
                state.pageIndex = res.data.pageSize
                state.pageIndex = res.data.pageNo
                state.totalPage = res.data.totalPage
                state.totalRows = res.data.totalRows
                loading.value = false
            }
            // console.log(state,'state')
        }

        /*** resetClick 重置按钮 */
        const resetClick = () => {
            searchOne.value = ''
            GetData(pageNo,pageSize)
        }

        /*** searchClick 查询按钮 */
        const searchClick = () => {
            GetData(pageNo,pageSize)
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                state.repeatDis = false
                GetInfo()
                GetData(pageNo,pageSize)
                state.ruleForm.InformStaffID = ''
                state.ruleForm.Company = ''
                state.ruleForm.CompanyNum = ''
                state.ruleForm.MaterialTypeIds = []
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            searchOne,
            ruleFormRef,
            ...toRefs(state),
            isUseDialog,
            rules,
            CompanyOptions,
            CompanyChange,
            InformStaffIDOptions,
            InformStaffIDChange,
            nameTextarea,
            codeTextarea,
            handleCurrentChange,
            handleSizeChange,
            addClick,
            confirm,
            nodeClick,
            getRowKey,
            handleSelectionChange,
            loading,
            resetClick,
            searchClick,
        }
    },
} )
</script>
<style scoped lang="scss">
    .wl-tyle{
        width: 100%;
        height: 36px;
        line-height: 36px;
        font-weight: 600;
        color: #04408c;
        background-color: #abc7ec;
        padding-left: 20px;
        margin-bottom: 10px;
    }
    :deep(.el-textarea__inner){
        min-height: 80px;
    }
</style>